package com.weiling.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weiling.entity.*;
import com.weiling.service.BsnsVideoService;
import com.weiling.util.DateUtil;
import com.weiling.util.QiniuUtils;
import com.weiling.util.StringUtil;
import com.weiling.util.VideoConverterUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/bsns/video")
public class BsnsVideoController {
    @Resource
    private BsnsVideoService bsnsVideoService;

    @Value("${qiniuHttp}")
    private String qiniuHttp;

    /**
     * 根据条件分页查询视频信息
     *
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('business:video:query') ")
    public R list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<BsnsVideo> pageResult = bsnsVideoService.page(new Page<>(pageBean.getPageNum(),
                pageBean.getPageSize()), new QueryWrapper<BsnsVideo>()
                .like(StringUtil.isNotEmpty(query), "name", query));
        List<BsnsVideo> videoList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("videoList", videoList);
        resultMap.put("total", pageResult.getTotal());
        return R.ok(resultMap);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('business:video:query')")
    public R findById(@PathVariable(value = "id") Integer id) {
        BsnsVideo bsnsVideo = bsnsVideoService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("bsnsVideo", bsnsVideo);
        return R.ok(map);
    }

    /**
     * 添加或者修改
     *
     * @param bsnsVideo
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('business:video:add')" + "||" + "hasAuthority('business:video:edit')")
    public R save(@RequestBody BsnsVideo bsnsVideo) {
        if (bsnsVideo.getId() == null || bsnsVideo.getId() == -1) {
            bsnsVideo.setCreateTime(new Date());
            bsnsVideoService.save(bsnsVideo);
        } else {
            bsnsVideo.setUpdateTime(new Date());
            bsnsVideoService.updateById(bsnsVideo);
        }
        return R.ok();
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('business:video:delete')")
    public R delete(@RequestBody Long[] ids) {
        bsnsVideoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 上传视频封面图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    @PreAuthorize("hasAuthority('business:video:add')" + "||" + "hasAuthority('business:video:edit')")
    public Map<String, Object> uploadImage(MultipartFile file) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        if (!file.isEmpty()) {
            String newFileName = UUID.randomUUID().toString();
            // 上传图片
            QiniuUtils.upload2Qiniu(file.getBytes(), newFileName);
            String coverUrl = qiniuHttp + newFileName;
            resultMap.put("code", 200);
            resultMap.put("msg", "上传成功");
            resultMap.put("url", coverUrl);
            return resultMap;
        }else {
            return R.error("上传图片失败");
        }
    }
    @RequestMapping("/uploadVideo")
    @PreAuthorize("hasAuthority('business:video:add')" + "||" + "hasAuthority('business:video:edit')")
    public Map<String, Object> uploadVideo(MultipartFile file) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        if (!file.isEmpty()) {
            String newFileName = UUID.randomUUID().toString();
            // 获取文件类型
            String fileContentType = file.getContentType();
            if (Objects.equals(fileContentType, "video/mp4")){
                // 转成webm格式，再上传视频
                byte[] webmData = VideoConverterUtil.mp4DataToWebmData(file.getBytes());
                if (webmData != null)
                    QiniuUtils.upload2Qiniu(webmData, newFileName);
                else
                    return R.error("上传视频失败");
            }else if (Objects.equals(fileContentType, "video/webm")){
                // 为webm格式，直接上传视频
                QiniuUtils.upload2Qiniu(file.getBytes(), newFileName);
            }else {
                return R.error("上传视频格式错误");
            }
            String url = qiniuHttp + newFileName;
            resultMap.put("code", 200);
            resultMap.put("msg", "上传成功");
            resultMap.put("url", url);
            return resultMap;
        }
        return R.error("上传视频失败");
    }
}
